﻿var currentStep = 1;
var maxSteps = 4;

$(function () {
    $("#breadcrumb").append('<li><a href="' + $("#urlReception").val() + '" title="Recepción">Recepción</a></li>');
    $("#optReception").addClass("HoverOnList");

    $("#txtBornDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    jQuery(function ($) {
        $.datepicker.regional['es'] = {
            closeText: 'Cerrar',
            prevText: '<Ant',
            nextText: 'Sig>',
            currentText: 'Hoy',
            monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
            monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
            dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
            dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mié', 'Juv', 'Vie', 'Sáb'],
            dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
            weekHeader: 'Sm',
            dateFormat: 'dd/mm/yy',
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: false,
            yearSuffix: ''
        };
        $.datepicker.setDefaults($.datepicker.regional['es']);
    });

    var validatorPerson = $("#frmPerson").bind("invalid-form.validate", function () {
        //$("#lblErrorMsgPerson").show();
    }).validate({
        debug: true,
        rules: {
            identification: {
                required: true,
                minlength: 2
            },
            name: {
                required: true,
                minlength: 1
            },
            firstName: {
                required: true,
                minlength: 1
            },
            lastName: {
                required: true,
                minlength: 1
            },
            bornDate: {
                required: false,
                date: true
            },
        },
        messages: {
            identification: "La identificación es requerido",
            name: "El nombre es requerido",
            firstName: "El primer apellido es requerido",
            lastName: "El segundo apellido es requerido",
            bornDate: "La fecha de nacimiento es incorrecta"
        }
    });

    var validatorContact = $("#frmContact").bind("invalid-form.validate", function () {
        //$("#frmContactErrorMessage").show();
    }).validate({
        debug: true,
        rules: {
            cmbCountry: 'required',
            txtCity: 'required',
            txtState: 'required',
            /*
            txtCity: {
                required: true,
                minlength: 5
            },
            txtState: {
                required: true,
                minlength: 5
            },
            txtDir1: {
                required: true,
                minlength: 5
            }
            */
        },
        messages: {
            cmbCountry: "El país es requerido",
            txtCity: "La ciudad es requerida",
            txtState: "La provincia/estado es requerida",
            txtDir1: "La dirección es requerida"
        }
    });

    var validatorLocalization = $("#frmLocalization").bind("invalid-form.validate", function () {
        //$("#lblErrorMsgLocalization").show();
    }).validate({
        debug: true,
        rules: {
            cmbLocalization: 'required',
            txtLocalization: {
                required: true,
                minlength: 5
            }
        },
        messages: {
            cmbLocalization: "El tipo de localización es requerida",
            txtLocalization: "El valor de la localización es requerida"
        }
    });

    var validatorCaregiver = $("#frmCaregiver").bind("invalid-form.validate", function () {
        //$("#lblErrorMsgLocalization").show();
    }).validate({
        debug: true,
        rules: {
            txtIdCaregiver: {
                required: true,
                minlength: 5
            },
            txtCaregiverName: {
                required: true,
                minlength: 1
            },
            txtFirstNameCaregivert: {
                required: true,
                minlength: 1
            },
            txtLastNameCaregiver: {
                required: true,
                minlength: 1
            },
            txtPhoneCaregiver1: {
                required: true,
                minlength: 5,
                digits: true
            },
            txtPhoneCaregiver2: {
                required: false,
                digits: true
            },
            txtEmailCaregiver: {
                required: false,
                email: true
            },
            cmbRelationShip: 'required'
        },
        messages: {
            txtIdCaregiver: "La identificación es requerida",
            txtCaregiverName: "El nombre es requerida",
            txtFirstNameCaregivert: "El primer apellido es requerido",
            txtLastNameCaregiver: "El segundo apellido es requerido",
            txtPhoneCaregiver1: "El teléfono es requerido",
            txtPhoneCaregiver2: "El teléfono es inválido",
            txtEmailCaregiver: "El correo electrónico es inválido",
            cmbRelationShip: "El parentesco es requerido"
        }
    });

    var validatorLocalizationEncargado = $("#frmLocalizationEncargado").bind("invalid-form.validate", function () {
        //$("#lblErrorMsgLocalization").show();
    }).validate({
        debug: true,
        rules: {
            cmbLocalizationEncargado: 'required',
            txtLocalizarionEncargado: {
                required: true,
                minlength: 5
            }
        },
        messages: {
            cmbLocalizationEncargado: "El tipo de localización es requerida",
            txtLocalizarionEncargado: "El valor de la localización es requerida"
        }
    });

    $('#chkIsNew').click(function () {
        if ($('#chkIsNew').is(':checked')) {
            $("#pnlCaregiver").show();
        }
        else {
            $("#pnlCaregiver").hide();
            $('#txtIdCaregiver').val('');
            $('#txtCaregiverName').val('');
            $('#txtFirstNameCaregivert').val('');
            $('#txtLastNameCaregiver').val('');
            $('#txtPhoneCaregiver1').val('');
            $('#txtPhoneCaregiver2').val('');
            $('#txtEmailCaregiver').val('');
        }
    });

    $('.item-del').live('click', function () {
        if (confirm('¿Esta seguro que desea eliminar el dato de contacto?')) {
            $(this).closest('li').remove();
        }
    });

    $('#nextStepTop').click(function () {
        NextStep();
    });

    $('#backStepTop').click(function () {
        BackStep();
    });

    $('#nextStepMiddle').click(function () {
        NextStep();
    });

    $('#backStepMiddle').click(function () {
        BackStep();
    });

    $('#btnNext').click(function () {
        NextStep();
    });

    $('#btnBack').click(function () {
        BackStep();
    });

    $('#btnClearPersonForm').live('click', function () {
        //ClearPersonForm();
    });

    $('#btnClearCaregiver').live('click', function () {
        ClearCaregiverForm();
    });

    $('#btnAddPerson').live('click', function () {
        AddPerson();
    });

    $('#btnEditPerson').live('click', function () {
        EditPerson();
    });

    $('#btnClearLocalization').live('click', function () {
        ClearLocalizationsForm();
    });

    $('#btnAddLocalization').live('click', function () {
        var type = parseInt($('#cmbLocalization').val());
        var value = $('#txtLocalization').val();
        var text = $('#cmbLocalization option:selected').text();
        AddLocalization(type, value, text);
    });

    $('#btnClearLocalizationEncargado').live('click', function () {
        ClearLocalizationsEncargadoForm();
    });

    $('#btnAddLocalizationEncargado').live('click', function () {
        var type = parseInt($('#cmbLocalizationEncargado').val());
        var value = $('#txtLocalizarionEncargado').val();
        var text = $('#cmbLocalizationEncargado option:selected').text();
        AddLocalizationEncargado(type, value, text);
    });

    $('#imgPhoto').live('click', function () {
        $("#filePhoto").trigger("click");
    });

    $('#btnStep1').live('click', function () {
        if (currentStep < maxSteps) {
            if (currentStep == 2 || currentStep == 3 || currentStep == 4)
                BackStep();
        }
    });

    $('#btnStep2').live('click', function () {
        if (currentStep < maxSteps) {
            if (currentStep == 1)
                NextStep();

            if (currentStep == 3)
                BackStep();
        }
    });

    $('#btnStep3').live('click', function () {
        if (currentStep < maxSteps) {
            if (currentStep == 1 || currentStep == 2)
                NextStep();
        }
    });

    $('#btnStep4').live('click', function () {
        if (currentStep < maxSteps) {
            if (currentStep == 1 || currentStep == 2)
                NextStep();
        }
    });

    $('#isExistingRecord').live('click', function () {
        $("#rdbNameFilter").removeAttr("disabled");
        $("#rdbID").removeAttr("disabled");
        $("#txtPersonFilter").removeAttr("disabled");

        $("#txtIdCaregiver").attr("disabled", "disabled");
        $("#txtCaregiverName").attr("disabled", "disabled");
        $("#txtFirstNameCaregivert").attr("disabled", "disabled");
        $("#txtLastNameCaregiver").attr("disabled", "disabled");

        $("#txtPhoneCaregiver1").attr("disabled", "disabled");
        $("#txtPhoneCaregiver2").attr("disabled", "disabled");
        $("#txtEmailCaregiver").attr("disabled", "disabled");

        $("#pnlTelephones").hide();
        $("#pnlEmail").hide();

        ClearCaregiverForm();
        $('#personID').val('');
    });

    $('#isNewRecord').live('click', function () {
        $("#rdbNameFilter").attr("disabled", "disabled");
        $("#rdbID").attr("disabled", "disabled");
        $("#txtPersonFilter").attr("disabled", "disabled");

        $("#txtIdCaregiver").removeAttr("disabled");
        $("#txtCaregiverName").removeAttr("disabled");
        $("#txtFirstNameCaregivert").removeAttr("disabled");
        $("#txtLastNameCaregiver").removeAttr("disabled");

        $("#txtPhoneCaregiver1").removeAttr("disabled");
        $("#txtPhoneCaregiver2").removeAttr("disabled");
        $("#txtEmailCaregiver").removeAttr("disabled");

        $("#pnlTelephones").show();
        $("#pnlEmail").show();

        $('#txtPersonFilter').val('');
        $('#txtIdCaregiver').val('');
        $('#txtCaregiverName').val('');
        $('#txtFirstNameCaregivert').val('');
        $('#txtLastNameCaregiver').val('');
        $('#txtPhoneCaregiver1').val('');
        $('#txtPhoneCaregiver2').val('');
        $('#txtEmailCaregiver').val('');

        $('#personID').val('');
        //ClearCaregiverForm();
    });

    //Error labels
    $("#lblErrorMsgPerson").hide();
    $("#lblsuccessMsgPerson").hide();
    $("#lblErrorMsgContact").hide();
    $("#lblsuccessMsgContact").hide();
    //$("#lblErrorMsgLocalization").hide();
    $("#lblsuccessMsgLocalization").hide();

    //Person
    $("#txtID").removeClass("error");
    $("#txtName").removeClass("error");
    $("#txtFirstName").removeClass("error");
    $("#txtLastName").removeClass("error");
    $("#txtBornDate").removeClass("error");
    $("#txtbirthPlace").removeClass("error");
    $("#cmbStatus").removeClass("error");
    $("#cmbCategory").removeClass("error");

    //Contact
    $("#cmbCountry").removeClass("error");
    $("#txtCity").removeClass("error");
    $("#txtState").removeClass("error");
    $("#txtPostalCode").removeClass("error");
    $("#txtDir1").removeClass("error");
    $("#txtDir2").removeClass("error");

    //Localization
    $("#cmbLocalization").removeClass("error");
    $("#txtLocalizarion").removeClass("error");

    //Back buttons
    $("#txtResponsable").attr("disabled", "disabled");
    $("#backStepTop").attr("disabled", "disabled");
    $("#backStepMiddle").attr("disabled", "disabled");
    $("#btnBack").attr("disabled", "disabled");

    var thumb = $('#imgPhoto');
    var thumb2 = $('#imgPhotoPreview');
    if (!(typeof thumb[0] === "undefined")) {
        new AjaxUpload('imgPhoto', {
            action: $("#urlUploadPhoto").val(),
            name: 'image',
            onSubmit: function (file, extension) { },
            onComplete: function (file, response) {
                $("#urlphoto").val(response);
                var url = '/ODSYSUI/Content/Images/Uploads/Customers/' + response;
                thumb.attr('src', url);
                thumb2.attr('src', url);
            }
        });
    }

    if (!(typeof $('#txtPersonFilter')[0] === "undefined")) {
        InitAutocomplete();
    }

    $("#txtID").blur(function () {
        CheckPersonIdentification($("#txtID").val());
    });
});

function HideStep(numStep) {
    switch (numStep) {
        case 1:
            $("#TitleStep1").hide();
            $("#frmPerson").hide();
            $("#btnStep1").addClass("disabled");
            break;

        case 2:
            $("#TitleStep2").hide();
            $("#frmCaregiver").hide();
            $("#btnStep2").addClass("disabled");
            break;

        case 3:
            $("#TitleStep3").hide();
            $("#frmContact").hide();
            $("#frmLocalization").hide();
            $("#btnStep3").addClass("disabled");
            break;

        case 4:
            $("#TitleStep4").hide();
            $("#frmConfirmation").hide();
            $("#btnStep4").addClass("disabled");
            break;
    }
}

function ShowStep(numStep) {
    switch (numStep) {
        case 1:
            $("#TitleStep1").show();
            $("#frmPerson").show();
            $("#btnStep1").removeClass("disabled");

            $("#backStepTop").attr("disabled", "disabled");
            $("#backStepMiddle").attr("disabled", "disabled");
            $("#btnBack").attr("disabled", "disabled");

            $("#stepstatus1").removeClass("status-ok");
            break;

        case 2:
            $("#TitleStep2").show();
            $("#frmCaregiver").show();
            $("#btnStep2").removeClass("disabled");
            $("#stepstatus1").addClass("status-ok");
            $("#stepstatus2").removeClass("status-ok");

            $("#backStepTop").removeAttr("disabled");
            $("#backStepMiddle").removeAttr("disabled");
            $("#btnBack").removeAttr("disabled");
            break;

        case 3:
            $("#TitleStep3").show();
            $("#frmContact").show();
            $("#frmLocalization").show();
            $("#btnStep3").removeClass("disabled");

            $("#stepstatus2").addClass("status-ok");

            $("#nextStepTop").removeAttr("disabled");
            $("#nextStepMiddle").removeAttr("disabled");
            $("#btnNext").removeAttr("disabled");
            break;
        case 4:
            $("#TitleStep4").show();
            $("#frmConfirmation").show();
            $("#btnStep4").removeClass("disabled");
            $("#stepstatus3").addClass("status-ok");

            $("#nextStepTop").attr("disabled", "disabled");
            $("#nextStepMiddle").attr("disabled", "disabled");
            $("#btnNext").attr("disabled", "disabled");
            break;
    }
}

function NextStep() {
    if (currentStep < maxSteps) {
        if (IsValidForm()) {
            HideStep(currentStep);
            currentStep++;

            if (currentStep == 4) {
                CopyLocalizationsStep3ToStep4();
                CopyFormData();
            }

            ShowStep(currentStep);
        }
    }
    return false;
}

function BackStep() {
    if (currentStep > 1) {
        HideStep(currentStep);
        currentStep--;

        if (currentStep == 3) {
            CopyLocalizationsStep4ToStep3();
        }

        ShowStep(currentStep);
    }
    return false;
}

function IsValidForm() {
    var isValid = false;
    switch (currentStep) {
        case 1:
            if ($('#chkKinship').is(':checked')) {
                if ($("#frmPerson").valid())
                    //$("#lblErrorMsgPerson").hide();
                    //$("#lblsuccessMsgPerson").hide();
                    isValid = true;
            }
            else {
                if ($("#frmPerson").valid())
                    isValid = true;
            }
            break;

        case 2:
            if ($("#frmContact").valid()) {
                //$("#lblErrorMsgContact").hide();
                //$("#frmContactErrorMessage").hide();

                isValid = true;
            }
            break;

        case 3:
            isValid = true;
            break;
    }

    return isValid;
}

function AddLocalization(type, value, text) {
    if ($("#frmLocalization").valid()) {
        var icon = "";
        var item = "";
        var item = "<li value='" + type + "' title='" + value + "'>" +
                    "<table style='width: 100%;'>" +
                        "<tr>" +
                            "<td style='width: 20%; text-align: left;'>" + $("#cmbLocalization option:selected").text() + "</td>" +
                            "<td style='width: 60%; text-align: left;'>" + value + "</td>" +
                            "<td></td>" +
                        "</tr>" +
                    "</table>" +
                    "<img class='item-del' width='16' height='16' src='/ODSYSUI/Content/images/icons/fugue/Delete.png' style='float: right; vertical-align: middle; margin-top: -15px; margin-left: 15px; cursor: pointer; border: 0px;'>" +
                "</li>";
        $("#localizationsList ul").append(item);
        ClearLocalizationsForm();
    }
}

function AddCaregiver() {
    var item = "";
    var isOk = false;

    if ($("#frmCaregiver").valid()) {
        if ($('#isExistingRecord').is(':checked')) {
            if ($("#txtPersonFilter").val() != '' && $("#txtPersonFilter").val() != 'undefined') {
                isOk = true;
            }
            else {
                alert('Debe ingresar el paciente');
            }
        }
        else {
            isOk = true;
        }

        if (isOk) {
            var caregiver = new Array();
            var allCaregivers = $('#CaregiverList li');
            var exist = false;

            allCaregivers.each(function () {
                var current = $(this);
                caregiver.push(current.attr("ident"));
            });

            for (var i = 0; i <= caregiver.length - 1; i++) {
                if (caregiver[i] == $('#txtIdCaregiver').val())
                    exist = true;
            }

            if (!exist) {
                var item = "<li isExistingRecord='" + $('#isExistingRecord').is(':checked') + "' ident='" + $('#txtIdCaregiver').val() + "' n='" + $('#txtCaregiverName').val() + "' fn='" + $('#txtFirstNameCaregivert').val() + "' ln='" + $('#txtLastNameCaregiver').val() + "' tel1='" + $('#txtPhoneCaregiver1').val() + "' tel2='" + $('#txtPhoneCaregiver2').val() + "' email='" + $('#txtEmailCaregiver').val() + "'>" +
                                "<table style='width: 100%;'>" +
                                    "<tr>" +
                                        "<td style='width: 20%; text-align: left;'>" + $('#txtIdCaregiver').val() + "</td>" +
                                        "<td style='width: 60%; text-align: left;'>" + ($('#txtCaregiverName').val() + ' ' + $('#txtFirstNameCaregivert').val() + ' ' + $('#txtLastNameCaregiver').val()) + "</td>" +
                                        "<td>" + $('#txtPhoneCaregiver1').val() + "</td>" +
                                    "</tr>" +
                                "</table>" +
                                "<img class='item-del' width='16' height='16' src='/ODSYSUI/Content/images/icons/fugue/Delete.png' style='float: right; vertical-align: middle; margin-top: -15px; margin-left: 15px; cursor: pointer; border: 0px;'>" +
                            "</li>";
                $("#lstCaregiverList").append(item);
                $('#txtIdCaregiver').val('');
                $('#txtCaregiverName').val('');
                $('#txtFirstNameCaregivert').val('');
                $('#txtLastNameCaregiver').val('');
                $('#txtPhoneCaregiver1').val('');
                $('#txtPhoneCaregiver2').val('');
                $('#txtEmailCaregiver').val('');
                $('#txtPersonFilter').val('');
                //$('#personID').val('');

                //var cmbRelationShip = $('#cmbRelationShip');
                //if (cmbRelationShip.length > 0) {
                //    cmbRelationShip[0].selectedIndex = 0;
                //}
            }
            else
                alert('Un encargardado del paciente con la misma identificación ya fue ingresado.');
        }
    }
}

function AddLocalizationEncargado(type, value, text) {
    if ($("#frmLocalizationEncargado").valid()) {
        var icon = "";
        var item = "";

        item = "<li class='" + icon + "' value='" + type + "' title='" + text + "'><span>" + value + "</span><img class='item-del' style='float: right; vertical-align: middle; margin-top: -14px; cursor: pointer; border: 0px;' src='/ODSYSUI/Content/images/icons/fugue/Delete.png' width='16' height='16'/></li>";
        $("#localizationsListEncargado ul").append(item);
        ClearLocalizationsEncargadoForm();
    }
}

function CopyLocalizationsStep3ToStep4() {
    var allLocalizations = $('#lstLocalizationsList li');
    $("#localizationsListPreview ul").append(allLocalizations);
    $("#lstLocalizationsListPreview").find(".item-del").hide();

    var lstCaregiverList = $('#lstCaregiverList li');
    $("#CaregiverListPreview ul").append(lstCaregiverList);
    $("#lstCaregiverListPreview").find(".item-del").hide();
}

function CopyLocalizationsStep4ToStep3() {
    var allLocalizations = $('#lstLocalizationsListPreview li');
    $("#localizationsList ul").append(allLocalizations);
    $("#lstLocalizationsList").find(".item-del").show();

    var CaregiverList = $('#lstCaregiverListPreview li');
    $("#CaregiverList ul").append(CaregiverList);
    $("#lstCaregiverList").find(".item-del").show();
}

function CopyFormData() {
    $('#txtIDResult').text($('#txtID').val());
    $('#txtNombreResult').text($('#txtName').val());
    $('#txtPrimerApellidoResult').text($('#txtFirstName').val());
    $('#txtSegundoApellidoResult').text($('#txtLastName').val());
    $('#txtFechaNacimientoResult').text(($('#txtBornDate').val() != '' && $('#txtBornDate').val() != 'undefined') ? $('#txtBornDate').val() : 'N/A.');

    var sex; if (($("#rdbMale").attr("checked") != "undefined" && $("#rdbMale").attr("checked") == "checked")) { sex = 'Masculino'; } else { sex = 'Femenino'; }
    $('#txtSexoResult').text(sex);

    $('#txtLugarNacimientoResult').text(($('#txtbirthPlace').val() != '' && $('#txtbirthPlace').val() != 'undefined') ? $('#txtbirthPlace').val() : 'N/A.');
    $('#txtEstadoCivilResult').text(($("#cmbStatus option:selected").text() != 'Seleccione' && $("#cmbStatus option:selected").text() != 'undefined') ? $("#cmbStatus option:selected").text() : 'N/A.');
    $('#txtCategoriaResult').text(($("#cmbCategory option:selected").text() != 'Seleccione' && $("#cmbCategory option:selected").text() != 'undefined') ? $("#cmbCategory option:selected").text() : 'N/A.');
    $('#txtTieneParentescoResult').text($('#chkKinship').is(':checked') ? 'Si' : 'No');

    //if ($('#chkKinship').is(':checked'))
    //    $('#txtEncargadoPacienteResult').text($('#txtNombreEncargado').val() + ' ' + $('#txtPrimerApellidoEncargado').val() + ' ' + $('#txtSegundoApellidoEncargado').val());

    $('#txtMedicoCabeceraResult').text($('#chkMedic').is(':checked') ? 'Si' : 'No');

    $('#txtCiudadResult').text(($('#txtCity').val() != 'undefined' && $('#txtCity').val() != '') ? $('#txtCity').val() : 'N/A.');
    $('#txtPaisResult').text(($("#cmbCountry option:selected").text() != 'Seleccione' && $("#cmbCountry option:selected").text() != 'undefined') ? $("#cmbCountry option:selected").text() : 'N/A.');
    $('#txtEstadoProvinciaResult').text(($('#txtState').val() != 'undefined' && $('#txtState').val() != '') ? $('#txtState').val() : 'N/A.');
    $('#txtCodigoPostalResult').text(($('#txtPostalCode').val() != '' && $('#txtPostalCode').val() != 'undefined') ? $('#txtPostalCode').val() : 'N/A.');
    $('#txtDireccion1Result').text(($('#txtDir1').val() != '' && $('#txtDir1').val() != 'undefined') ? $('#txtDir1').val() : 'N/A.');
    $('#txtDireccion2Result').text(($('#txtDir2').val() != '' && $('#txtDir2').val() != 'undefined') ? $('#txtDir2').val() : 'N/A.');
}

function AddPerson() {
    CreatePerson();
}

function ClearPersonForm() {
    ClearLocalizationsForm();
    ClearEncargadoForm();
    ClearContactForm();
    PreviewForm();

    var $radios = $('input:radio[name=rdbSex]');
    $radios.filter('[value=male]').attr('checked', true);

    var cmbStatus = $('#cmbStatus');
    cmbStatus[0].selectedIndex = 0;

    var cmbCategory = $('#cmbCategory');
    cmbCategory[0].selectedIndex = 0;

    var cmbCountry = $('#cmbCountry');
    cmbCountry[0].selectedIndex = 0;

    var cmbCity = $('#txtCity');
    cmbCity[0].selectedIndex = 0;

    var cmbState = $('#txtState');
    cmbState[0].selectedIndex = 0;

    $('#txtID').val('');
    $('#txtName').val('');
    $('#txtFirstName').val('');
    $('#txtLastName').val('');
    $('#txtBornDate').val('');
    $('#txtbirthPlace').val('');
    $('#chkMedic').attr('checked', false);
    $('#chkKinship').attr('checked', false);

    //$('#txtCity').val('');
    //$('#txtState').val('');
    $('#txtPostalCode').val('');
    $('#txtDir1').val('');
    $('#txtDir2').val('');

    //$("#lblErrorMsgPerson").hide();
    //$("#lblsuccessMsgPerson").hide();

    $("#txtID").removeClass("error");
    $("#txtName").removeClass("error");
    $("#txtFirstName").removeClass("error");
    $("#txtLastName").removeClass("error");
    $("#txtBornDate").removeClass("error");
    $("#txtbirthPlace").removeClass("error");
    $("#cmbStatus").removeClass("error");
    $("#cmbCategory").removeClass("error");

    $("#txtCity").removeClass("error");
    $("#txtState").removeClass("error");
    $("#txtPostalCode").removeClass("error");
    $("#txtDir1").removeClass("error");
    $("#txtDir2").removeClass("error");

    $("#frmPerson").find(".error").remove();
    //$("#frmEncargado").find(".error").remove();
    $("#frmContact").find(".error").remove();

    $('#lstLocalizationsList li').remove();
    $('#lstLocalizationsListPreview li').remove();
}

function CreatePerson() {
    var date = '';
    var bornDate = new Date();

    var values = new Array();
    var caregiver = new Array();

    var allLocalizations = $('#lstLocalizationsListPreview li');
    var allCaregivers = $('#lstCaregiverListPreview li');

    if ($("#txtBornDate").val() != '' && $("#txtBornDate").val() != 'undefined') {
        date = $("#txtBornDate").val().split("/");
        bornDate = new Date(date[2], date[1] - 1, date[0]);
    }

    allLocalizations.each(function () {
        var current = $(this);
        var item = current.attr("value") + ";" + current.attr("title") + ";";
        values.push(item);
    });

    allCaregivers.each(function () {
        var current = $(this);
        var item = current.attr("isexistingrecord") + ";" + current.attr("ident") + ";" + current.attr("n") + ";" + current.attr("fn") + ";" + current.attr("ln") + ";" + current.attr("tel1") + ";" + current.attr("tel2") + ";" + current.attr("email") + ";";
        caregiver.push(item);
    });

    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlCreate").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                identification: $('#txtID').val(),
                name: $('#txtName').val(),
                firstName: $('#txtFirstName').val(),
                lastName: $('#txtLastName').val(),
                picture: $('#urlphoto').val(),
                birthDate: bornDate,
                sex: (($("#rdbMale").attr("checked") != "undefined" && $("#rdbMale").attr("checked") == "checked")) ? true : false,
                birthPlace: $('#txtbirthPlace').val(),
                maritalStatusID: $('#cmbStatus').val(),
                personTypeID: $('#cmbCategory').val(),
                indMedic: $('#chkMedic').val(),
                countryID: $('#cmbCountry').val(),
                state: $('#txtState').val(),
                city: $('#txtCity').val(),
                postalCode: $('#txtPostalCode').val(),
                address1: $('#txtDir1').val(),
                address2: $('#txtDir2').val(),
                localizationValues: values,
                //caregivers: caregiver,
                responsables: caregiver
            }),
        success: function (data, status) {
            window.location = $("#urlReception").val();
        },
        error: function (data, status, e) {
            alert(e);
        }
    });
}

function ClearCaregiverForm() {
    $('#isExistingRecord').attr('checked', true);

    $("#rdbNameFilter").removeAttr("disabled");
    $("#rdbID").removeAttr("disabled");
    $("#txtPersonFilter").removeAttr("disabled");

    $("#txtIdCaregiver").attr("disabled", "disabled");
    $("#txtCaregiverName").attr("disabled", "disabled");
    $("#txtFirstNameCaregivert").attr("disabled", "disabled");
    $("#txtLastNameCaregiver").attr("disabled", "disabled");
    $("#txtPhoneCaregiver1").attr("disabled", "disabled");
    $("#txtPhoneCaregiver2").attr("disabled", "disabled");
    $("#txtEmailCaregiver").attr("disabled", "disabled");

    $("#pnlTelephones").hide();
    $("#pnlEmail").hide();

    $('#txtPersonFilter').val('');
    $('#personID').val('');
    $("#rdbNameFilter").removeAttr("disabled");
    $("#rdbID").removeAttr("disabled");

    $('#txtIdCaregiver').val('');
    $('#txtCaregiverName').val('');
    $('#txtFirstNameCaregivert').val('');
    $('#txtLastNameCaregiver').val('');
    $('#txtPhoneCaregiver1').val('');
    $('#txtPhoneCaregiver2').val('');
    $('#txtEmailCaregiver').val('');

    $('#txtIdCaregiver').removeClass("error");
    $('#txtCaregiverName').removeClass("error");
    $('#txtFirstNameCaregivert').removeClass("error");
    $('#txtLastNameCaregiver').removeClass("error");
    $('#txtPhoneCaregiver1').removeClass("error");
    $('#txtPhoneCaregiver2').removeClass("error");
    $('#txtEmailCaregiver').removeClass("error");

    $("#frmCaregiver").find(".error").remove();
}

function ClearLocalizationsForm() {
    var cmbLocalization = $('#cmbLocalization');
    cmbLocalization[0].selectedIndex = 0;

    $('#txtLocalization').val('');
    $("#txtLocalization").removeClass("error");
    $("#cmbLocalization").removeClass("error");
    $("#frmLocalization").find(".error").remove();

    //$("#lblErrorMsgLocalization").hide();
    //$("#lblsuccessMsgLocalization").hide();
}

function ClearLocalizationsEncargadoForm() {
    var cmbLocalizationEncargado = $('#cmbLocalizationEncargado');
    cmbLocalizationEncargado[0].selectedIndex = 0;

    //$("#lblErrorMsgLocalization").hide();
    //$("#lblsuccessMsgLocalization").hide();

    $('#txtLocalizarionEncargado').val('');
    $("#txtLocalizarionEncargado").removeClass("error");
    $("#cmbLocalizationEncargado").removeClass("error");
    $("#frmLocalizationEncargado").find(".error").remove();
}

function ClearEncargadoForm() {
    ClearLocalizationsEncargadoForm()

    $('#txtIDEncargado').val('');
    $('#txtNombreEncargado').val('');
    $('#txtPrimerApellidoEncargado').val('');
    $('#txtSegundoApellidoEncargado').val('');

    $("#txtIDEncargado").removeClass("error");
    $("#txtNombreEncargado").removeClass("error");
    $("#txtPrimerApellidoEncargado").removeClass("error");
    $("#txtSegundoApellidoEncargado").removeClass("error");

    // $("#frmEncargado").find(".error").remove();
    $('#lstLocalizationsListEncargado li').remove();
}

function ClearContactForm() {
    ClearLocalizationsForm();

    var cmbCountry = $('#cmbCountry');
    cmbCountry[0].selectedIndex = 0;

    var cmbState = $('#txtState');
    cmbState[0].selectedIndex = 0;

    var cmbCity = $('#txtCity');
    cmbCity[0].selectedIndex = 0;

    //$('#txtCity').val('');
    //$('#txtState').val('');
    $('#txtPostalCode').val('');
    $('#txtDir1').val('');
    $('#txtDir2').val('');

    //$("#lblErrorMsgPerson").hide();
    //$("#lblsuccessMsgPerson").hide();

    $("#txtID").removeClass("error");
    $("#txtName").removeClass("error");
}

function PreviewForm() {
    $('#txtIDResult').text('');
    $('#txtNombreResult').text('');
    $('#txtPrimerApellidoResult').text('');
    $('#txtSegundoApellidoResult').text('');
    $('#txtFechaNacimientoResult').text('');
    $('#txtSexoResult').text('');
    $('#txtLugarNacimientoResult').text('');
    $('#txtEstadoCivilResult').text('');
    $('#txtCategoriaResult').text('');
    $('#txtTieneParentescoResult').text('');
    $('#txtEncargadoPacienteResult').text('');
    $('#txtMedicoCabeceraResult').text('');
    $('#txtCiudadResult').text('');
    $('#txtPaisResult').text('');
    $('#txtEstadoProvinciaResult').text('');
    $('#txtCodigoPostalResult').text('');
    $('#txtDireccion1Result').text('');
    $('#txtDireccion2Result').text('');
}

// ****************************************************************************
// *********** Editar Informacion Paciente ************************************
// ****************************************************************************

function EditPerson() {
    var date = '';
    var bornDate = new Date();

    var values = new Array();
    var caregiver = new Array();

    var allLocalizations = $('#lstLocalizationsListPreview li');
    var allCaregivers = $('#lstCaregiverListPreview li');

    if ($("#txtBornDate").val() != '' && $("#txtBornDate").val() != 'undefined') {
        date = $("#txtBornDate").val().split("/");
        bornDate = new Date(date[2], date[1] - 1, date[0]);
    }

    allLocalizations.each(function () {
        var current = $(this);
        var item = current.attr("value") + ";" + current.attr("title") + ";";
        values.push(item);
    });

    allCaregivers.each(function () {
        var current = $(this);
        var item = current.attr("isexistingrecord") + ";" + current.attr("Relationtype") + ";" + current.attr("id") + ";" + current.attr("ident") + ";" + current.attr("n") + ";" + current.attr("fn") + ";" + current.attr("ln") + ";" + current.attr("tel1") + ";" + current.attr("tel2") + ";" + current.attr("email") + ";";
        caregiver.push(item);
    });

    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlEdit").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                personID: $('#IDPerson').val(),
                identification: $('#txtID').val(),
                name: $('#txtName').val(),
                firstName: $('#txtFirstName').val(),
                lastName: $('#txtLastName').val(),
                picture: $('#urlphoto').val(),
                birthDate: bornDate,
                sex: (($("#rdbMale").attr("checked") != "undefined" && $("#rdbMale").attr("checked") == "checked")) ? true : false,
                birthPlace: $('#txtbirthPlace').val(),
                maritalStatusID: $('#cmbStatus').val(),
                personTypeID: $('#cmbCategory').val(),
                indMedic: $('#chkMedic').val(),
                countryID: $('#cmbCountry').val(),
                state: $('#txtState').val(),
                city: $('#txtCity').val(),
                postalCode: $('#txtPostalCode').val(),
                address1: $('#txtDir1').val(),
                address2: $('#txtDir2').val(),
                localizationValues: values,
                responsables: caregiver
            }),
        success: function (data, status) {
            window.location = $("#urlReception").val();
        },
        error: function (data, status, e) {
            alert(e);
        }
    });
}

function InitAutocomplete() {
    //debugger;
    $("#txtPersonFilter").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: $('#urlGetPatients').val(),
                dataType: "json",
                data: {
                    searchString: request.term,
                    IsByName: $('#rdbNameFilter').is(':checked'),
                    maxRows: 12
                },
                parse: function (data) {
                    var rows = new Array();
                    for (var i = 0; i < data.length; i++) {
                        rows[i] = { data: data[i], value: data[i].name, result: data[i].name };
                    }
                    return rows;
                },
                success: function (data) {
                    //debugger;
                    response($.map(data, function (item) {
                        return {
                            label: item.name + " " + item.firstName + " " + item.lastName + ". ID: " + item.identification,
                            ID: item.personID,
                            Name: item.name,
                            FirstName: item.firstName,
                            LastName: item.lastName,
                            Identification: item.identification,
                            DefaultPhone: item.defaultPhone
                        }
                    }));
                },
                error: function (data, status, e) {
                    debugger;
                    alert(e);
                }
            });
        },
        minLength: 0,
        select: function (event, ui) {
            $("#txtIdCaregiver").val(ui.item.Identification);
            $("#txtCaregiverName").val(ui.item.Name);
            $("#txtFirstNameCaregivert").val(ui.item.FirstName);
            $("#txtLastNameCaregiver").val(ui.item.LastName);
            $("#txtPhoneCaregiver1").val(ui.item.DefaultPhone);
            $('#personID').val(ui.item.ID);
        }
    });

    $("#txtPersonFilter").keyup(function () {
        if (!this.value) {
            $('#personID').val();
        }
    });
}

function CheckPersonIdentification(identification) {
    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlCheckPersonIdentification").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                identification: $('#txtID').val(),
            }),
        success: function (data, status) {
            if (data.Error && (data.Msg != '')) {
                alert(data.Msg);
            }
            else {
                if ((data.Exists)) {
                    $("#lblErrorMsg").show(300).delay(5000).hide(400);
                    $("#txtID").addClass("error");
                    $("#btnNext").attr("disabled", "disabled");
                    $("#nextStepTop").attr("disabled", "disabled");
                }
                else {
                    $("#txtID").removeClass("error");
                    $("#btnNext").removeAttr("disabled");
                    $("#nextStepTop").removeAttr("disabled");
                }
            }
        },
        error: function (data, status, e) {
            alert(e);
        }
    });
}